import { FC, useState } from 'react';
import { Layout, Card, Button, Table, Space, Upload, Input, message } from 'antd';
import { 
  UploadOutlined, 
  DeleteOutlined, 
  EditOutlined,
  DownloadOutlined,
  SearchOutlined,
  BarChartOutlined,
  RightOutlined,
  LeftOutlined
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import MainLayout from '../../components/MainLayout';
import TrendChart from './components/TrendChart';
import { PatentFile } from './types/index';
import styles from './TrendAnalysis.module.css';
import type { ColumnsType } from 'antd/es/table';

const { Sider, Content } = Layout;
const { Search } = Input;

const TrendAnalysis: FC = () => {
  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [files, setFiles] = useState<PatentFile[]>([]);
  const [loading, setLoading] = useState(false);
  const [siderCollapsed, setSiderCollapsed] = useState(false);
  const [showAnalysis, setShowAnalysis] = useState(false);

  const columns: ColumnsType<PatentFile> = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      width: '50%',
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      width: '30%',
      render: (time: string) => new Date(time).toLocaleDateString(),
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
      render: (_: any, record: PatentFile) => (
        <Space size={4}>
          <Button 
            type="text" 
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          />
          <Button 
            type="text" 
            size="small"
            icon={<DownloadOutlined />}
            onClick={() => handleDownload(record)}
          />
        </Space>
      ),
    },
  ];

  const uploadProps: UploadProps = {
    accept: '.pdf,.docx,.txt,.md',
    showUploadList: false,
    beforeUpload: (file) => {
      const isValidType = [
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'text/plain',
        'text/markdown'
      ].includes(file.type);

      if (!isValidType) {
        message.error('只支持 PDF、Word、TXT 和 Markdown 文件！');
        return Upload.LIST_IGNORE;
      }

      // 模拟上传
      const newFile: PatentFile = {
        id: Date.now().toString(),
        name: file.name,
        type: file.name.split('.').pop() || '',
        size: file.size,
        uploadTime: new Date().toLocaleString(),
        url: URL.createObjectURL(file)
      };

      setFiles(prev => [...prev, newFile]);
      return false;
    }
  };

  const handleEdit = (file: PatentFile) => {
    // 实现编辑功能
  };

  const handleDelete = (file: PatentFile) => {
    setFiles(prev => prev.filter(f => f.id !== file.id));
    message.success('删除成功');
  };

  const handleDownload = (file: PatentFile) => {
    window.open(file.url);
  };

  const handleBatchAction = (action: 'delete' | 'download' | 'analyze') => {
    switch (action) {
      case 'delete':
        setFiles(prev => prev.filter(f => !selectedFiles.includes(f.id)));
        message.success('批量删除成功');
        setShowAnalysis(false);
        break;
      case 'download':
        selectedFiles.forEach(id => {
          const file = files.find(f => f.id === id);
          if (file) handleDownload(file);
        });
        break;
      case 'analyze':
        setShowAnalysis(true);
        break;
    }
    setSelectedFiles([]);
  };

  return (
    <MainLayout>
      <Layout className={styles.analysisLayout}>
        <div className={styles.siderWrapper}>
          <Sider 
            width={400} 
            className={styles.sider}
            collapsible
            collapsed={siderCollapsed}
            collapsedWidth={0}
            trigger={null}
          >
            <Card 
              title="专利文档管理" 
              bordered={false}
              bodyStyle={{ padding: '12px' }}
              extra={
                <Upload {...uploadProps}>
                  <Button size="small" icon={<UploadOutlined />}>上传</Button>
                </Upload>
              }
            >
              <div className={styles.batchActions}>
                <Space>
                  <Button 
                    disabled={selectedFiles.length === 0}
                    onClick={() => handleBatchAction('delete')}
                    icon={<DeleteOutlined />}
                  >
                    批量删除
                  </Button>
                  <Button 
                    disabled={selectedFiles.length === 0}
                    onClick={() => handleBatchAction('download')}
                    icon={<DownloadOutlined />}
                  >
                    批量下载
                  </Button>
                  <Button 
                    type="primary"
                    disabled={selectedFiles.length === 0}
                    onClick={() => handleBatchAction('analyze')}
                    icon={<BarChartOutlined />}
                  >
                    分析趋势
                  </Button>
                </Space>
              </div>
              <Table
                rowSelection={{
                  selectedRowKeys: selectedFiles,
                  onChange: (selectedRowKeys) => 
                    setSelectedFiles(selectedRowKeys as string[]),
                }}
                columns={columns}
                dataSource={files}
                rowKey="id"
                size="small"
                pagination={false}
                scroll={{ y: 'calc(100vh - 300px)' }}
              />
            </Card>
          </Sider>
          <Button
            className={siderCollapsed ? styles.collapseButtonLeft : styles.collapseButtonRight}
            type="text"
            icon={siderCollapsed ? <RightOutlined /> : <LeftOutlined />}
            onClick={() => setSiderCollapsed(!siderCollapsed)}
          />
        </div>
        <Content className={styles.content}>
          <Card 
            title="趋势分析" 
            className={styles.analysisCard}
          >
            {showAnalysis && selectedFiles.length > 0 ? (
              <TrendChart fileIds={selectedFiles} />
            ) : (
              <div className={styles.placeholder}>
                {selectedFiles.length > 0 
                  ? '请点击"分析趋势"按钮进行分析'
                  : '请选择文件进行趋势分析'
                }
              </div>
            )}
          </Card>
        </Content>
      </Layout>
    </MainLayout>
  );
};

export default TrendAnalysis; 